import {scheduleUpdateOnFiber} from './ReactFiberWorkLoop'

let currentlyRenderingFaber = null
let workInProgressHook = null

export function renderHooks(wip) {
    currentlyRenderingFaber = wip
    currentlyRenderingFaber.memoizedState = null // 第0个hook
    workInProgressHook = null
}

function updateWorkInProgressHook() {
    console.log('~~workInProgressHook',workInProgressHook)
    let hook;
    const current = currentlyRenderingFaber.alterNate
    if (current) {
        // 更新fiber
        currentlyRenderingFaber.memoizedState = current.memoizedState
        if (workInProgressHook) { // 不是第0个hook
            hook = workInProgressHook = workInProgressHook.next
        } else {// 第0个hook
            hook = workInProgressHook = current.memoizedState
        }
    } else {
        // 初次渲染fiber
        hook = {
            memoizedState: null,
            next: null
        }
        if (workInProgressHook) { // 不是第0个hook
            workInProgressHook = workInProgressHook.next = hook
        } else { // 第0个hook
            workInProgressHook = currentlyRenderingFaber.memoizedState = hook
        }
    }
    return hook
}

// 函数组件第一次被执行或更新时
export const useReducer = (reducer, initialState) => {

    const hook = updateWorkInProgressHook()
    // 初次渲染
    if(!currentlyRenderingFaber.alterNate){
        hook.memoizedState = initialState
    }
    const dispatch = (action) => {
        console.log('~~dispatch', initialState)
        hook.memoizedState = reducer(hook.memoizedState,action)
        // 重置根节点
        scheduleUpdateOnFiber(currentlyRenderingFaber)
    }

    return [hook.memoizedState, dispatch]
}